package com.termux.utils

import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit


object CommandUtil {
    @Throws(IOException::class)
    fun run(command: String): String {
        var input: Scanner? = null
        var result = ""
        var process: Process? = null
        try {
            process = Runtime.getRuntime().exec(command)
            try {
                //等待命令执行完成
                process.waitFor(10, TimeUnit.SECONDS)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            val `is` = process.inputStream
            input = Scanner(`is`)
            while (input.hasNextLine()) {
                result += """
                    ${input.nextLine()}
                    
                    """.trimIndent()
            }
            result = """
                $command
                $result
                """.trimIndent() //加上命令本身，打印出来
        } finally {
            input?.close()
            process?.destroy()
        }
        return result
    }

    @Throws(IOException::class)
    fun run(command: Array<String?>): String {
        var input: Scanner? = null
        var result = ""
        var process: Process? = null
        try {
            process = Runtime.getRuntime().exec(command)
            try {
                //等待命令执行完成
                process.waitFor(10, TimeUnit.SECONDS)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            val `is` = process.inputStream
            input = Scanner(`is`)
            while (input.hasNextLine()) {
                result += """
                    ${input.nextLine()}
                    
                    """.trimIndent()
            }
            result = """
                $command
                $result
                """.trimIndent() //加上命令本身，打印出来
        } finally {
            input?.close()
            process?.destroy()
        }
        return result
    }
}